package com.example.designpattern.iterator;


import java.util.Arrays;

/**
 * 用迭代器模式的实现
 */
public class IteratorPatternDemo {
    public static void main(String[] args) {
        Student student1 = new Student("小明");
        Student student2 = new Student("小王");

        Classroom classroom = new Classroom(2);
        classroom.addStudent(student1);
        classroom.addStudent(student2);

        Iterator iterator = classroom.iterator();
        while(iterator.hasNext()){
            Student student = (Student) iterator.next();
            System.out.println(student);
        }
    }

    /**
     * 学生类
     */
    public static class Student{
        private String name;

        public Student(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    /**
     * 定义一个迭代器借口, 包含两个方法： 是否有下一个元素；返回下一个元素
     */
    public interface Iterator{
        public boolean hasNext();
        public Object next();
    }

    /**
     * 代表了一个集合类
     */
    public interface Aggregate{
        public Iterator iterator();
    }

    /**
     * 教师类
     */
    public static class Classroom implements Aggregate{

        private Student[] students;
        
        private int last = 0;
        
        public Classroom(int size){
            this.students = new Student[size];
        }
        
        public Student getStudent(int index){
            return students[index];
        }
        public void addStudent(Student student){
            this.students[last] = student;
            last++;
        }
        public int getLength(){
            return last;
        }

        /**
         * 返回一个教室迭代器，其中封装了教室自己，让迭代器可以获取教室中的数据
         * @return
         */
        public Iterator iterator() {
            return new ClassroomIterator(this);
        }
        
    }

    /**
     * 教师迭代器
     */
    public static class ClassroomIterator implements Iterator{

        private Classroom classroom;
        private int index;

        public ClassroomIterator(Classroom classroom) {
            this.classroom = classroom;
            this.index = 0;
        }

        public boolean hasNext() {
            if(index<classroom.getLength()){
                return true;
            }else{
                return false;
            }
        }

        public Object next() {
            Student student = classroom.getStudent(index);
            index++;
            return student;
        }
    }
}
